//设置根路径
axios.defaults.baseURL = 'http://ajax-base-api-t.itheima.net'

const tb = document.querySelector('#tb');
const form = document.querySelector('#bookForm');
const render = () => {
  axios.get('/api/getbooks').then(({ data: res }) => {
    const { data } = res
      const html= data.map(item => {
        return `<tr>
        <td>${item.id}</td>
        <td>${item.bookname}</td>
        <td>${item.author}</td>
        <td>${item.publisher}</td>
        <td><a href="#" data-id="${item.id}">删除</a></td>
         </tr>`
      }).join('')
      tb.innerHTML = html
    })
}
render()
form.addEventListener('submit', function (e) {
  e.preventDefault()
  const obj = serialize(form, { hash: true })
  axios.post('/api/addbook', obj).then(({ data: res }) => {
    if (res.status !== 201) return alert(res.msg)
    render()
     form.reset()
   })
  tb.addEventListener('click', function (e) {
    if (e.target.tagName === 'A') {
      const id = e.target.dataset.id
      axios.get(`/api/delbook?id=${id}`).then(({ data: res }) => render())
     }
  })

   })
const choose = document.querySelector('#btnChoose');
choose.addEventListener('click', function () {
   const cho=serialize(form,{hash:true})
  axios.get('/api/getbooks', {params:cho}).then(( { data: res } ) => {
    console.log(res);
    const { data } = res 
    const html= data.map(item => {
      return `<tr>
      <td>${item.id}</td>
      <td>${item.bookname}</td>
      <td>${item.author}</td>
      <td>${item.publisher}</td>
      <td><a href="#" data-id="${item.id}">删除</a></td>
    </tr>
`
}).join('')
tb.innerHTML = html
  })
})